package sun.cn.common.cacheDto.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.BinaryJedis;

/**
 * redis工具类
 * 
 * @author sunlingao
 * @title
 * @date 2017年7月8日
 * @version
 */
public class RedisUtils {

	private static final Logger LOG = LoggerFactory.getLogger(RedisUtils.class);

	private RedisUtils(){}

	/** 过期时间 */
	private static final int EXPIRETIME = 60 * 30;

	public static void setKey(String key, Object value, BinaryJedis jedis) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("set key is {} value is {}", key, JSON.toJSONString(value));
		}
		if (StringUtils.isNotEmpty(key) && !key.endsWith("null") && value != null) {
            jedis.set(SerializeUtils.toBytes(key), SerializeUtils.toBytes(value));
		}
	}

	public static void delKey(String key,BinaryJedis jedis) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("del key is {}", key);
		}
        jedis.del(SerializeUtils.toBytes(key));
	}

	public static Object getKey(String key,BinaryJedis jedis) {
		if (StringUtils.isBlank(key))
			return null;
		byte[] result = jedis.get(SerializeUtils.toBytes(key));
		if (LOG.isDebugEnabled()) {
			LOG.debug("get key is {} value is {}", key, result == null ? "null" : "not null");
		}
		return result == null ? null : SerializeUtils.toObject(result);
	}

	public static void delHset(String key, String field,BinaryJedis jedis) {
		if (StringUtils.isBlank(key) || StringUtils.isBlank(field))
			return;
        jedis.hdel(SerializeUtils.toBytes(key), SerializeUtils.toBytes(field));
	}

	public static Object hGet(String key, String field,BinaryJedis jedis) {
		Object result = SerializeUtils
				.toObject(jedis.hget(SerializeUtils.toBytes(key), SerializeUtils.toBytes(field)));
		if (LOG.isDebugEnabled()) {
			LOG.debug("hGet key is {} field is {} value is {}", new Object[]{key,field,JSON.toJSONString(result)});
		}
		/** 重置热点数据过期时间 */
		if(result != null){
            jedis.expire(SerializeUtils.toBytes(key), EXPIRETIME);
		}
		return result;
	}

	public static void hSet(String key, String field, Object value,BinaryJedis jedis) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("hSet key is {} field is {} value is {}",new Object[]{key,field,value});
		}
        jedis.hset(SerializeUtils.toBytes(key), SerializeUtils.toBytes(field), SerializeUtils.toBytes(value));
        jedis.expire(SerializeUtils.toBytes(key), EXPIRETIME);
	}
	
	public static boolean setnx(String key,Object value,int expireTime,BinaryJedis jedis){
		boolean flag = false;
		if (LOG.isDebugEnabled()) {
			LOG.debug("setnx key is {} value is {}", key, value);
		}
		Long result = jedis.setnx(SerializeUtils.toBytes(key), SerializeUtils.toBytes(value));
		flag = (result == 1L)?true:false;
		if(flag && expireTime > 0)
            jedis.expire(SerializeUtils.toBytes(key), expireTime);
		return flag;
	}

}
